package org.mytools.dao.gener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mytools.dao.gener.meta.ColumnData;

/**
 * MYBATIS的SQL映射包装类
 * 
 * @author Jacky.L
 * 
 */
public class MapperWrapper {

	private static final String NAME_SUFFIX = "Mapper";
	private static final String MAPPER_SUFFIX = ".xml";
	private static final String QUERY_SEPARATOR = ".";
	private static final String TEMPLATE_NAME = "mapper.vm";

	private static Log logger = LogFactory.getLog(MapperWrapper.class);

	/**
	 * 返回域对象的SQL Mapper名称
	 * 
	 * @param domainName
	 *            域对象名称
	 * @return SQL Mapper名称
	 */
	public static String getMapperName(String domainName) {
		StringBuffer mapperName = new StringBuffer(domainName);
		mapperName.append(NAME_SUFFIX);

		return mapperName.toString();
	}

	/**
	 * 返回域对象的SQL Mapper语句名称
	 * 
	 * @param domainName
	 *            域对象名称
	 * @param query
	 *            语句名称
	 * @return SQL Mapper语句名称
	 */
	public static String getMapperQuery(String domainName, String query) {
		StringBuffer mapperQueryName = new StringBuffer(
				getMapperName(verifyDomainName(domainName)));
		mapperQueryName.append(QUERY_SEPARATOR);
		mapperQueryName.append(query);
		logger.debug("###Current MapperQueryName: "
				+ mapperQueryName.toString());
		return mapperQueryName.toString();
	}

	/**
	 * 校验并修正域对象名称
	 * 
	 * @param domainName
	 *            域对象名称
	 * @return 合法的域对象名称
	 */
	private static String verifyDomainName(String domainName) {
		StringBuffer verifyName = new StringBuffer();
		char[] chars = domainName.toCharArray();
		for (char ch : chars) {
			if (Character.isLetter(ch) || Character.isDigit(ch)) {
				verifyName.append(ch);
			} else {
				break;
			}
		}
		return verifyName.toString();
	}

	/**
	 * 返回SQL Mapper文件的后缀名
	 * 
	 * @return SQL Mapper文件的后缀名
	 */
	public static String getMapperSuffix() {
		return MAPPER_SUFFIX;
	}

	/**
	 * 返回SQL Mapper文件的生产模板的全路径名称，包括模板的名称
	 * 
	 * @param vmPath
	 *            模板路径
	 * @return 模板的全路径名称
	 */
	public static String getMapperTemplate(String vmPath) {
		return new StringBuffer().append(vmPath).append("/")
				.append(TEMPLATE_NAME).toString();
	}

	/**
	 * 返回SQL Mapper的数据库column的比较值
	 * 
	 * @param column
	 *            数据库列对象
	 * @return 数据库column的比较值
	 */
	public static String getMapperCompareValue(ColumnData column) {
		String comparevalue = null;
		if (column.getJavaTypeName().equals("short")
				|| column.getJavaTypeName().equals("int")
				|| column.getJavaTypeName().equals("long")) {
			comparevalue = "0";
		} else if (column.getJavaTypeName().equals("float")
				|| column.getJavaTypeName().equals("double")) {
			comparevalue = "0.0";
		} else {
			comparevalue = "null";
		}
		return comparevalue;
	}

}
